var express = require('express');
var router = express.Router();

var Category = require('../models/Category');
var Content = require('../models/Content');

var data;

/*
* 处理通用的数据
* */
router.use(function (req, res, next) {
    data = {
        userInfo: req.userInfo,
        categories : [],
    };

    Category.find().then(function (categories) {
        data.categories = categories;
        next();
    });
})

/*
* 首页
* */
router.get('/', function (req, res) {

    data.page = Number(req.query.page || 1),
    data.categoryType = req.query.categoryType || '',
    data.limit = 10,
    data.totalPage = 0

    var where = {};
    if(data.categoryType){
        where.category = data.categoryType
    }

    // 读取数据库中的内容信息
    Content.where(where).count().then(function (count) {
        data.count = count;
        data.totalPage = Math.ceil(data.count/data.limit);
        data.page = Math.min( data.page, data.totalPage );
        data.page = Math.max( data.page, 1 );
        var skip = (data.page - 1)*data.limit;
        return Content.where(where).find().limit(data.limit).skip(skip).sort({addTime:-1}).populate(['category', 'user']);
    }).then(function (contents) {

        data.contents = contents;
        res.render('main/index', data);
    })
});

router.get('/view', function (req, res) {
   
    var contentId = req.query.contentid || '';
    
    Content.findOne({
        _id: contentId
    }).then(function (content) {
        data.content = content;

        content.views++;
        content.save();

        res.render('main/view', data);
    })
    
});

module.exports = router;